package answer

import "fmt"

func main() {
	l1 := new(ListNode)
	numsA := []int{1, 2, 3}
	l1.AddListNode(numsA)

	l2 := new(ListNode)
	numsB := []int{1, 3, 5}
	l2.AddListNode(numsB)
	mergeTwoLists(l1, l2).printNode()
}

type ListNode struct {
	Val  int
	Next *ListNode
}

/**
 * @Description: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
func mergeTwoListsByIteration(l1 *ListNode, l2 *ListNode) *ListNode {
	result := new(ListNode)
	temp := result
	for l1 != nil && l2 != nil {
		temp.Next = new(ListNode)
		temp = temp.Next

		if l1.Val < l2.Val {
			temp.Val = l1.Val
			l1 = l1.Next
		} else {
			temp.Val = l2.Val
			l2 = l2.Next
		}
	}

	for l1 != nil {
		temp.Next = new(ListNode)
		temp = temp.Next
		temp.Val = l1.Val
		l1 = l1.Next
	}

	for l2 != nil {
		temp.Next = new(ListNode)
		temp = temp.Next
		temp.Val = l2.Val
		l2 = l2.Next
	}

	return result.Next
}

func (node *ListNode) AddListNode(nums []int) {
	other := node
	for _, value := range nums {
		temp := new(ListNode)
		temp.Val = value
		other.Next = temp
		other = temp
	}
}

func (node *ListNode) printNode() {
	for node != nil {
		fmt.Println(node.Val)
		node = node.Next
	}
}
